/**
 * tjftp -- A simple FTP server, using the ANSI C
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include "sockets.h"
int tj_port_get_client_port(char* str) {
	int p1 = 0;
	int p2 = 0;
	char* pointer = strtok(str, ",");
	while (pointer != NULL) {
		p1 = p2;
		p2 = atoi(pointer);
		pointer = strtok(NULL, ",");
	}
	return p1 * 256 + p2;
}
void tj_port_get_ip_from_address(char buffer[], char result[]) {
	int i;
	int count = 0;
	for (i = 0; i < strlen(buffer); i++) {
		if (buffer[i] == ',') {
			count++;
			if (4 == count) {
				break;
			}
			result[i] = '.';
		} else {
			result[i] = buffer[i];
		}
	}
}
void tj_port_send_message(char* port_address, char* info) {
	char ip[255] = { '\0' };
	strcpy(ip, port_address);
	int port = tj_port_get_client_port(ip);
	memset(ip, '\0', 255);
	tj_port_get_ip_from_address(port_address, ip);
	int fd = tj_create_tcp_socket();
	tj_tcp_open_connect(fd, ip, port);
	send(fd, info, strlen(info) + 1, 0);
	tj_sockets_close(fd);
}
